layui.use(['table','layer','form', 'layedit','jquery'], function(){
    var table = layui.table
        ,layer = layui.layer
        ,form = layui.form
        ,layedit = layui.layedit
        ,$ = layui.jquery;

    var body = "";
    var checkStatus;//多选框选中状态
    var checkedData = "";
    //判断是否有选中行，没有得话则把修改按钮置灰
    $(function(){
        //获取到选中数据
        checkedData = layui.table.checkStatus('dictionary_table').data;
    });
    table.render({
        elem: '#dictionary_table'
        ,url:'../user/queryUserlimit'
        ,response: {
            statusName: 'code'
            ,statusCode: '100012'
            ,msgName: 'msg'
            ,countName: 'total'
            ,dataName: 'data'
        }
        ,toolbar: '#toolbar'
        ,title: '字典类型'
        ,cols: [[
            {type: 'checkbox', fixed: 'left'}
            ,{field:'user_id', title:'用户编码',sort: true, fixed: 'left'}
            ,{field:'username', title:'用户名称', fixed: 'left'}
            ,{field:'account', title:'登录账号', fixed: 'left'}
            ,{field:'phone', title:'手机号码', fixed: 'left'}
            ,{field:'user_status_id', title:'用户状态', fixed: 'left',templet:function (d) {
                    if(d.user_status_id==1)
                    {
                        return '启用';
                    }else{
                        return '禁用';
                    }
                }}
            ,{field:'description', title:'用户角色', fixed: 'left'}
            ,{field:'create_time', title:'创建时间', templet : "<div>{{layui.util.toDateString(d.create_time, 'yyyy-MM-dd HH:mm:ss')}}</div>", fixed: 'left'}
            ,{field:'job_number', title:'工号', fixed: 'left'}
            ,{fixed: 'right', title:'操作', toolbar: '#operations'}
        ]]
        ,page: true
        ,id: 'table'
        ,limit:15
        ,limits:[15,20,30,40]
        ,skin: 'line'
    });

    //打开弹出层表单
    function openForm(title,event,url1,url2,params){
        layer.open({
            type: 2,
            area:['90%', '60%'],
            fixed:true,
            anim: 2,
            offset: '100px',
            maxmin:false,
            scrollbar: false,
            title: title,
            content: ['/page/addUser.html','no'],
           end: function () {
               location.reload();
            },
           btn:['确认','取消'],
            success: function(layero, index) {
                //设置body为全局变量
                body = layer.getChildFrame('body',index);
                switch (event) {
                    case 'add_user':
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.getRole(roleId);
                        break;
                    case 'update_user':
                        var userId="";
                        var roleId="";
                        $.each($.parseJSON(params),function (i,v) {
                            userId=v.user_id;
                            roleId=v.role_id;
                        })
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.getRole(roleId);
                        iframeWin.getUser(userId);
                        break;
                }
            },
            yes: function(index, layero){
                switch (event) {
                    case 'add_user':
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.addUser();
                        break;
                    case 'update_user':
                        //var data = checkStatus.data;
                        var userId="";
                        $.each($.parseJSON(params),function (i,v) {
                            userId=v.user_id;
                        });
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        iframeWin.upUserOrRole(userId);
                        break;
                }
            }
            ,btn2: function(index, layero){
                layer.close(index);
                return false;
            }
        });
    }

    //删除选中行同时兼容多选和单选
    function delDicTypeByIds(url,idsStr){
        $.ajax({
            url:url,
            type:'post',
            async:true,
            data:{userId:idsStr},
            timeout:5000,    //超时时间
            dataType:'json', //返回的数据格式：json/xml/html/script/jsonp/text
            success:function(res){
                if(res.success){
                   layer.msg('用户删除成功！',{offset: '220px'});
                        //执行重载
                        table.reload('table', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        }, 'data');
                }else
                {
                    layer.msg('用户删除失败！',{offset: '220px'});
                }
            },
            error:function(data){
                layer.msg('删除失败!',{offset: '220px'});
            }
        });
    }

    //头工具栏事件
    table.on('toolbar(dictionary_table)', function(obj){
        //设置选中状态为全局变量
        checkStatus = table.checkStatus(obj.config.id);
    /*  这两行报错有问题  var index = parent.layer.getFrameIndex(window.name);
        parent.layer.iframeAuto(index);*/
        switch(obj.event){
            case 'getCheckData':
                var data = checkStatus.data;
                layer.alert(JSON.stringify(data));
                break;
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：'+ data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选': '未全选');
                break;
            case 'add_user':
                openForm('新增员工信息','add_user','../dictionaryType/getMaxDIC_id.json','../dictionaryType/addDictionaryType.json',null);
                break;
            case 'update_user':
                var params = JSON.stringify(checkStatus.data);
                if(params.length>2&&params.length<350)
                {
                    openForm('修改员工信息','update_user',null,null,params);
                }else if(params.length==2){
                    layer.msg("请选择用户！",{offset: '220px'});
                }else
                {
                    alert(params.length);
                    layer.msg("修改用户不能选择多个哦！",{offset: '220px'});
                }
                break;
            case 'delete_user':
                //获取要删除的行id
                var delData = checkStatus.data;
               if(delData.length>0)
               {
                   var delStr = "";
                   //解析要删除的数据
                   $.each(delData,function(index,value){
                       delStr+=value.user_id+',';
                   });
                   //进一步处理要删除的数据行的id
                   delStr = delStr.substring(0,delStr.length-1);
                   //询问是否要真的删除
                   layer.confirm('是否删除选中用户',{offset: '320px'}, function(index){
                       delDicTypeByIds('https://linliny.com.cn:8443/superllny/user/delUser',delStr);
                       layer.close(index);
                   });
               }else
               {
                   layer.msg("请选择用户！",{offset: '220px'});
               }
                break;
        };
    });

    //监听行工具事件
    table.on('tool(dictionary_table)', function(obj){
        var data = obj.data;
        //console.log(obj)
        if(obj.event === 'del'){
            layer.confirm('是否删除选中用户',{offset: '320px'}, function(index){
                delDicTypeByIds('../user/delUser',data.user_id);
                layer.close(index);
            });
        } else if(obj.event === 'edit'){
           var array=new Array();
           array.push(data);
           var params=JSON.stringify(array);
            openForm('修改员工信息','update_user',null,null,params);
        }else if(obj.event==='addRole')
        {
            layer.open({
                type: 2,
                closeBtn: 1,
                offset: '100px',
                title: "树形菜单",
                area: ['16%','38%'],
                content: ['/page/one.html','no'],
                //btn:['确认','取消'],
                success: function(layero, index){

                }
            });
        }
    });
});

